package be.scond.cartpool;

import java.io.IOException;
import javax.servlet.http.*;
import be.scond.cartpool.API.GroupApi;
import be.scond.cartpool.exceptions.GroupDoesNotExistException;
import be.scond.cartpool.exceptions.GroupExistsException;
import be.scond.cartpool.exceptions.GroupPassIncorrectException;
import be.scond.cartpool.exceptions.UserExistsException;
import be.scond.utils.CheckEmail;

public class RegisterServlet extends HttpServlet {
	
	static final long serialVersionUID = 1;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/xml");
		

		String groupName = req.getParameter("groupName");
		String userName = req.getParameter("userName");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		String groupPass = req.getParameter("groupPass");
		
		String respons = "<data>";	

		if(CheckEmail.check(email)){
			try {
				GroupApi.register(userName, email, password, groupName, groupPass);
				respons += "<succes>registering of group with name "+groupName+" succeeded</succes>";				
			} catch (GroupDoesNotExistException e) {
				respons += "<error>The group with name: " + groupName + " does not exist</error>";
			} catch (GroupExistsException e) {
				respons += "<error>The group with name: " + groupName + " already exists, fill out the key for this group to become part of it.</error>";
			} catch (UserExistsException e) {
				respons += "<error>Failed to register user with group "+groupName+", email: " + email + " or userName: "+userName+" already exists for this group</error>";
			} catch (GroupPassIncorrectException e) {
				respons += "<error>Failed to register user with group "+groupName+", The provided groupKey was incorrect</error>";
			}
		}else{
			respons += "<error>"+email+" is not a valid email adress</error>";
		}

			
		respons += "</data>";

		resp.getWriter().print(respons);
	}
}